package com.yqya.springboot.shiro.practice.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.yqya.springboot.shiro.practice.domain.UserInfo;
import com.yqya.springboot.shiro.practice.domain.UserRelateRoleInfo;
import com.yqya.springboot.shiro.practice.service.UserInfoService;
import com.yqya.springboot.shiro.practice.service.UserRelateRoleInfoService;

import cn.hutool.core.collection.CollUtil;

/**
 * 用户认证
 *
 * @author Kevin
 * @date 2019-07-28
 */
public class UserAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRelateRoleInfoService userRelateRoleInfoService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        UserInfo user = userInfoService.findByName(name);
        Long userId = user.getId();

        List<UserRelateRoleInfo> userRelateRoleList = userRelateRoleInfoService.listByUserId(userId);
        // 添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if (CollUtil.isNotEmpty(userRelateRoleList)) {
            // 测试代码 todo 待实现
            // 添加角色
            simpleAuthorizationInfo.addRole("管理员");
            // 添加角色的权限编码
            simpleAuthorizationInfo.addStringPermission("100100");

        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }

        // 获取用户信息
        String name = authenticationToken.getPrincipal().toString();
        UserInfo user = userInfoService.findByName(name);
        if (user == null) {
            // 返回后会报出对应异常
            return null;
        } else {
            // 验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name,
                    user.getPwd(), getName());
            return simpleAuthenticationInfo;
        }
    }

}
